import random

import cv2
import numpy
import matplotlib.pyplot as plt
import numpy as np


# 使用PIL库函数读取图片，保障读取出的图片对象的模式为RGB
# def openpecture1(image_name):
#     img = Image.open(image_name)
#     return img

# 在终端显示图片 image:图片矩阵 image_name:图片名称
def pshow(image, image_name):
    # 转换为RGB模式的图片
    if image_name.endswith('jpg'):  # 如果是jpg，需要进行转换
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    plt.imshow(image)
    plt.axis('off')
    plt.title('RGB')
    plt.show()


# 使用窗口显示图像，img图片矩阵
def show_in_window(img):
    # 更改窗口大小，使窗口可调节
    # 占满整个屏幕将0换为cv2.WINDOW_NORMAL
    cv2.namedWindow("image", 0)
    cv2.imshow('image', img)
    # 0表示无限等待用户按键，改为k，则kms后关闭窗口
    cv2.waitKey(0)
    cv2.destroyAllWindows()


# 保存图像，img：图片矩阵，name：图片要保存为的名称
def savepeacture(img, name):
    cv2.imwrite(name, img)


# 截取部分图像 img：图片矩阵 返回截取好的图片矩阵
def cutpeacture(img):
    # 截取图像高1600——2700，宽3500-4500位置
    cat = img[1600:2700, 3500:4500]
    return cat


# 获取图像大小（shape),img:图像矩阵 返回值：图像高、宽、通道数（RGB为3个通道）
def Getshape(img):
    return img.shape


image_name = "yes.png"

# img = cv2.imread(image_name)
# pshow(img,image_name)
# show_in_window(img)

# 此处为覆盖保存，自动覆盖同名文件
# name='mysife.png'
# savepeacture(img, name)

# 截取测试
# cat = cutpeacture(img)
# pshow(cat,image_name)

from PIL import Image
import os


def convert(directory):
    # 遍历目录下所有文件
    for filename in os.listdir(directory):
        # 获取文件扩展名
        extension = os.path.splitext(filename)[1].lower()
        print("文件:" + filename + "已读取")
        # 如果文件不是 JPG 类型，则进行转换
        if extension not in ['.jpg', '.jpeg', '.png', '.gif']:
            print("文件" + filename + "不是图片文件，请重新上传")
            break
        if extension not in [".jpg", ".jpeg"]:
            # 打开图像文件
            image = Image.open(os.path.join(directory, filename))
            # 转换图像格式为 JPG
            image = image.convert('RGB')
            new_filename = os.path.splitext(filename)[0] + ".jpg"
            image.save(os.path.join(directory, new_filename), "JPEG")
            os.remove(os.path.join(directory, filename))
            print("图像文件:" + new_filename + "转换格式成功")
            # 关闭图像文件
            image.close()
        else:
            print("图像文件:" + filename + "已经是Jpg格式")
        # 删除原始文件


# image = cv2.imread('white.png')
# print(image)
def tackle(image1, image2):
    np.set_printoptions(threshold=np.inf, linewidth=np.inf)
    try:
        pixel_diff = cv2.absdiff(image1, image2)
        savepeacture(pixel_diff, 'image.jpg')
    except cv2.error as e:
        return print("匹配不成功")

    # 遍历每一行的像素值，并计算像素值之和
    image = cv2.imread('image.jpg')
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    ret, image = cv2.threshold(image, 150, 255, cv2.THRESH_BINARY)
    row_sums = []
    for row in image:
        row_sum = np.sum(row)
        row_sums.append(row_sum)
    # 将每一行的像素值之和存储在新的数组中
    row_sums_array = np.array(row_sums)

    # 找出像素值之和不为 0 的行，并将它们合并成一个新的图像
    nonzero_indices = np.where(row_sums_array >= 66)[0]

    # 获取图像的高度和宽度
    height, width = image.shape[:2]
    horizontal_values = image[np.arange(height), :]
    # print(horizontal_values)
    # 定义一个新的空白图像，大小与原图相同
    new_image = np.zeros((len(nonzero_indices), width, 3), np.uint8)
    new_image.fill(255)
    i = 0
    # 遍历每个像素，将其像素值填充到新图像中
    for y in nonzero_indices:
        for x in range(width):
            pixel_value = horizontal_values[y][x]
            new_image[i][x] = pixel_value
        i = i + 1

    # 显示结果图像
    show_in_window(new_image)
    stra = 'result' + str(random.randint(1, 100)) + '.jpg'
    cv2.imwrite('test.jpg', new_image)
    cv2.imwrite('result\\' + stra, new_image)
    print('匹配成功')
    print("提取后的图片文件" + stra + "已保存")


def convert_test():
    convert("jpgfile")  # 测试jpg文件
    convert("notjpgfile")  # 测试非jpg文件
    convert("notpicture")  # 测试非图片文件


from flask import Flask, request, jsonify

app = Flask(__name__)


@app.route('/api/endpoint', methods=['POST'])
def api_endpoint():
    convert_test()
    convert("question")
    convert("daan")
    for question_file in os.listdir("question"):
        for answer_file in os.listdir("daan"):
            image1 = cv2.imread("question" + '\\' + question_file)
            image2 = cv2.imread("daan" + '\\' + answer_file)
            tackle(image1, image2)
    return jsonify({'result': 'success'})


if __name__ == '__main__':
    convert_test()
    convert("question")
    convert("daan")
    for question_file in os.listdir("question"):
        for answer_file in os.listdir("daan"):
            image1 = cv2.imread("question" + '\\' + question_file)
            image2 = cv2.imread("daan" + '\\' + answer_file)
            tackle(image1, image2)
